'use strict';

angular.module('sakuraApp')
    .controller('TradeItemController', function ($scope, TradeItem, User, Trade, Item, ItemSpec, ItemInfo, TradeItemSearch, ParseLinks) {
        $scope.tradeItems = [];
        $scope.users = User.query();
        $scope.trades = Trade.query();
        $scope.items = Item.query();
        $scope.itemspecs = ItemSpec.query();
        $scope.iteminfos = ItemInfo.query();
        $scope.page = 1;
        $scope.loadAll = function() {
            TradeItem.query({page: $scope.page, per_page: 20}, function(result, headers) {
                $scope.links = ParseLinks.parse(headers('link'));
                for (var i = 0; i < result.length; i++) {
                    $scope.tradeItems.push(result[i]);
                }
            });
        };
        $scope.reset = function() {
            $scope.page = 1;
            $scope.tradeItems = [];
            $scope.loadAll();
        };
        $scope.loadPage = function(page) {
            $scope.page = page;
            $scope.loadAll();
        };
        $scope.loadAll();

        $scope.showUpdate = function (id) {
            TradeItem.get({id: id}, function(result) {
                $scope.tradeItem = result;
                $('#saveTradeItemModal').modal('show');
            });
        };

        $scope.save = function () {
            if ($scope.tradeItem.id != null) {
                TradeItem.update($scope.tradeItem,
                    function () {
                        $scope.refresh();
                    });
            } else {
                TradeItem.save($scope.tradeItem,
                    function () {
                        $scope.refresh();
                    });
            }
        };

        $scope.delete = function (id) {
            TradeItem.get({id: id}, function(result) {
                $scope.tradeItem = result;
                $('#deleteTradeItemConfirmation').modal('show');
            });
        };

        $scope.confirmDelete = function (id) {
            TradeItem.delete({id: id},
                function () {
                    $scope.reset();
                    $('#deleteTradeItemConfirmation').modal('hide');
                    $scope.clear();
                });
        };

        $scope.search = function () {
            TradeItemSearch.query({query: $scope.searchQuery}, function(result) {
                $scope.tradeItems = result;
            }, function(response) {
                if(response.status === 404) {
                    $scope.loadAll();
                }
            });
        };

        $scope.refresh = function () {
            $scope.reset();
            $('#saveTradeItemModal').modal('hide');
            $scope.clear();
        };

        $scope.clear = function () {
            $scope.tradeItem = {itemPrice: null, ctime: null, disabled: null, id: null};
            $scope.editForm.$setPristine();
            $scope.editForm.$setUntouched();
        };
    });
